#!/usr/bin/env python3.8
# -*- encoding: utf-8 -*-
'''
@File    :   fakes.py
@Time    :   2021/10/13 16:49:09
@Author  :   windstarry 
@Version :   1.0
'''
#import os
import random

from faker import Faker
from flask import current_app
from sqlalchemy.exc import IntegrityError

from albumy.extensions import db
from albumy.models import User,Role

fake = Faker()


def fake_admin():
    admin = User(name='admin',
                username='admin',
                email='liefengwind@163.com',
                bio=fake.sentence(),
                location=fake.city(),
                website=fake.url(),
                member_since=fake.date_this_decade(),
                confirmed=True)
    admin.set_password('123456')
    db.session.add(admin)
    db.session.commit()


def fake_user(count=10):
    for i in range(count):
        user = User(name=fake.name(),
                    confirmed=True,
                    username=fake.user_name(),
                    bio=fake.sentence(),
                    location=fake.city(),
                    website=fake.url(),
                    member_since=fake.date_this_decade(),
                    email=fake.email())
        user.set_password('123456')
        db.session.add(user)
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()



def init_role_permissions():
    for user in User.query.all():
        if user.role is None:
            if user.email == current_app.config['ALBUMY_ADMIN_EMAIL']:
                user.role = Role.query.filter_by(name='Administrator').first()
            else:
                user.role = Role.query.filter_by(name='User').first()
        db.session.add(user)
    db.session.commit()